package me.spring.cloud.common.components.oss.cloud;

import me.spring.cloud.common.components.util.constant.CharConstant;
import me.spring.cloud.common.components.util.enums.FileTypeEnum;
import me.spring.cloud.common.components.util.io.FileHelper;
import me.spring.cloud.common.components.util.lang.RandomUtil;
import me.spring.cloud.common.components.util.lang.StringUtil;
import java.net.URL;
import javax.validation.constraints.NotNull;
import lombok.Data;

/**
 * @description: 基础方法
 * @author: luffy
 * @create: 2018-09-20 13:50
 **/
@Data
public abstract class AbstractCloudStoreServiceImpl implements CloudStorageService {

  private OssCloudConfig config;

  public String getPath(String prefix, String suffix) {
    return StringUtil.append(StringUtil.join(CharConstant.SLASH, prefix, suffix, RandomUtil.randomStringLength(11)),
        String.valueOf(CharConstant.DOT), suffix);
  }

  /**
   * @param fileName 文件名称
   * @param mimeType 文件类型
   * @Return java.lang.String
   * @Author luffy
   * @Description 构造文件名称
   * @Date 2019-07-06 17:08
   */
  protected String constructFileName(String fileName, @NotNull String mimeType) {
    if (StringUtil.isEmpty(fileName)) {
      fileName = RandomUtil.randomStr(20);
    }
    if (!fileName.contains(String.valueOf(CharConstant.DOT))) {
      fileName = StringUtil.append(fileName, FileTypeEnum.getSuffixByMime(mimeType));
    }
    return fileName;
  }

  @Override
  public String uploadForRemoteSrcUrl(String webUrl,String fileName) throws Exception {
    return uploadForInputStream(new URL(webUrl).openStream(), FileHelper.parseSuffix(webUrl), null);
  }
}
